﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMS.Common.ServiceModel;

namespace SMS.Common.Search
{
    /// <summary>
    /// 默认搜索提供者
    /// </summary>
    /// <typeparam name="T">搜索的实体类型</typeparam>
    public abstract class DefualtSearchProvider<T> : ISearchProvider<T>
    {
        #region ISearchProvider<T> 成员

        /// <summary>
        /// 根据条件搜索视图并返回结果,若条件本身是搜索提供者则使用条件本身进行搜索，
        /// 否则如果是StringFilterCondition或DarkSearchCondition，则使用指定规则搜索。
        /// 找不到匹配的搜索提供者将执行NoMatchSearchProvider操作。
        /// </summary>
        /// <param name="condition">搜索条件</param>
        /// <returns>返回搜索视图的结果</returns>
        public SearchResult<T> Search(SearchCondition condition)
        {            
            SearchResult<T> sr = null;
            if (condition is ISearchProvider<T>)
            {
                ISearchProvider<T> sp = condition as ISearchProvider<T>;
                sr = sp.Search(condition);
            }
            else if (condition is StringFilterCondition)
            {
                StringFilterCondition filter = condition as StringFilterCondition;
                sr = SearchByStringFilter(filter);
            }
            else if (condition is DarkSearchCondition)
            {
                DarkSearchCondition darkCondition = condition as DarkSearchCondition;
                sr = SearchByDarkCondition(darkCondition);
            }
            else
            {
                sr = NoMatchSearchProvider(condition);
            }
            return sr;
        }

        /// <summary>
        /// 未找到匹配搜索提供者时执行该操作。
        /// </summary>
        protected virtual SearchResult<T> NoMatchSearchProvider(SearchCondition condition)
        {
            throw new InvalidateException(Properties.Resources.Exception_NoMatchSearchProvider);
        }

        /// <summary>
        /// 根据模糊条件搜索结果。
        /// </summary>
        /// <param name="darkCondition">模糊条件</param>
        protected abstract SearchResult<T> SearchByDarkCondition(DarkSearchCondition darkCondition);

        /// <summary>
        /// 根据字符筛选条件搜索结果。
        /// </summary>
        /// <param name="filter">字符筛选条件</param>
        /// <returns></returns>
        protected abstract SearchResult<T> SearchByStringFilter(StringFilterCondition filter);
        #endregion
    }
}
